﻿using LD.Host;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace LD
{
    public class UdpClientEx : BaseCommunication
    {
        private Socket socket = null;
        private IPEndPoint endPoint = null;
        private IPAddress ip;
        public UdpClientEx(TcpIpParameModel parame)
        {
            Parame = parame;
            ip = IPAddress.Parse(parame.Ip);
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            endPoint = new IPEndPoint(ip, parame.Port);
            socket.SendTimeout = 1000;
            socket.ReceiveTimeout = 2000;
        }
        public override void Connect()
        {
            try
            {
                socket.Connect(endPoint);
                base.ConnectionStateEvent?.Invoke(Parame.Name, socket.Connected ? Status.成功 : Status.失败);
            }
            catch (Exception)
            {
            }
        }
        public TcpIpParameModel Parame { get; private set; }

        public override object Send(string content)
        {
            if (socket.Connected)
            {
                byte[] data = null;
                Log4.Info($"【{Parame.Name}】发送:{content}");
                byte[] msgBytes = Encoding.ASCII.GetBytes(content);
                this.socket.SendTo(msgBytes, this.endPoint);

                EndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);
                byte[] buf = new byte[this.socket.ReceiveBufferSize];
                Task.Delay(20).Wait();

                if (socket.Available > 0)
                {
                    int bufLen = socket.ReceiveFrom(buf, ref endPoint);

                    if (buf != null &&
                        buf.Count<byte>() > 26 &&
                        BitConverter.ToInt16(new List<byte> { buf[25], buf[24] }.ToArray(), 0) * 2 + 26 == bufLen)
                    {
                        data = new byte[bufLen];
                        Array.Copy(buf, data, bufLen);
                        string result = BitConverter.ToString(data);
                        Log4.Info($"【{Parame.Name}】接收:{result}");
                    }
                }
                else
                {
                    Log4.Warr($"【{Parame.Name}】未收到电批信息");
                }
            }
            else
            {
                Connect();
            }
            return string.Empty;
        }
    }
}
